package com.ken.mqbase.returnlistener;

import com.ken.constant.RabbitConstant;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.QueueingConsumer.Delivery;

/**
 * return机制 消费者
 * Created by renchongyu on 2018/11/15.
 */
public class ConsumerReturn {

    public static void main(String[] args) throws Exception{
        //1.创建一个ConnectionFactory
        ConnectionFactory conn = new ConnectionFactory();
        conn.setHost(RabbitConstant.RABBITMQ_IP);
        conn.setPort(RabbitConstant.RABBITMQ_PORT);
        conn.setUsername(RabbitConstant.RABBITMQ_USER_NAME);
        conn.setPassword(RabbitConstant.RABBITMQ_USER_PASSWORD);
        conn.setVirtualHost(RabbitConstant.RABBITMQ_VIRTUAL_HOST);

        //2.通过连接工厂连接
        Connection connection = conn.newConnection();

        //3.通过连接创建一个channel
        Channel channel = connection.createChannel();

        String exchangeName = "test_return_exchange";
        String routingKey = "return.#";
        String queueName = "test_return_queue";
        channel.exchangeDeclare(exchangeName,"topic",true,false,null);
        channel.queueDeclare(queueName,true,false,false,null);
        channel.queueBind(queueName,exchangeName,routingKey);

        QueueingConsumer queueingConsumer = new QueueingConsumer(channel);

        channel.basicConsume(queueName,true,queueingConsumer);

        while (true){
            Delivery delivery = queueingConsumer.nextDelivery();
            String msg = new String(delivery.getBody());
            System.out.println(msg);
        }
    }
}
